# Views for the Hegelian Inquiry Tool
# @author: Richard Cornelissen

from django.http import HttpResponse, HttpResponseServerError, HttpResponseRedirect,\
    HttpResponseForbidden, HttpResponseNotFound
from django.contrib.auth.decorators import login_required
from django.template import RequestContext, loader
from django import forms
from triangulators import *
from models import *
from HIT.metasearch import metasearch
import simplejson
from django.core.urlresolvers import reverse
import AlchemyAPI
from elementtree.ElementTree import Element, XML

from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render_to_response

forbiddenSubjects = ["battle", "who", "one", "what", "me", "itself", "it", "i", "we" , "you", "they", "he", "that", "which",  "this" , "this option", "for themselves", "the report", "all of them", "her words", "the stakes", "us"]
forbiddenVerbs = ["be", "have", "go", "underlines", "need", "set", "do", "has", "put"]

class QueryForm(forms.Form):
    query = forms.CharField()

class LinkForm(forms.Form):
    link = forms.CharField()

class InvestigatorForm(forms.Form):
    first_name = forms.CharField(required = False)
    last_name = forms.CharField(required = False)
    location = forms.CharField(required = False)
    domain = forms.CharField(required = False)

class StartTriangulationForm(forms.Form):
    subject = forms.CharField(max_length = 500, min_length = 2)
    thesis = forms.CharField(widget=forms.Textarea)

class StartAntithesisTriangulationForm(forms.Form):
    antithesis = forms.CharField(widget=forms.Textarea)

class SynthesisForm(forms.Form):
    synthesis = forms.CharField(widget=forms.Textarea, required = False)

def javascript(request, file):
    t = loader.get_template(file)
    c = RequestContext(request, {})
    return HttpResponse(t.render(c), mimetype='application/javascript')

'''
View for the home screen
@param request Data about the request made by the user
'''
def home(request):
    results = None
    if request.user.is_authenticated():
        triangulations = HegelianTriangulation.objects.filter(user = request.user).extra(select={'subject_upper':'upper(subject)'}).order_by('-subject_upper', '-date')
        
        results = {}
        for t in triangulations:
            if not results.has_key(str(t.subject)):
                results[str(t.subject)] = []
                results[str(t.subject)].append(t)
            print results
    
    t = loader.get_template('base.html')
    c = RequestContext(request, {'results': results,
                                 'helptext': reverse('HIT.Triangulator.views.helptext', args=['home']),})
    return HttpResponse(t.render(c))

@login_required
def start_triangulation(request):
    t = loader.get_template('start_triangulation.html')
    f = StartTriangulationForm()
    c = RequestContext(request, {'form': f,
                                 'helptext': reverse('HIT.Triangulator.views.helptext', args=['starttriangulation']),
                                 'next': reverse('HIT.Triangulator.views.query_or_select')})
    return HttpResponse(t.render(c))

'''
View for the start of the triangulation process.
Gives the user the choice to start triangulating a link or to search for a link on the internet through some keywords and metasearch
@param request Data about the request made by the user
'''
@login_required
def query_or_select(request):
    f = StartTriangulationForm(request.POST)
    if f.is_valid():
        ht = HegelianTriangulation(user = request.user, subject = f.cleaned_data['subject'], thesis = f.cleaned_data['thesis'])
        ht.save()
        request.session.set_expiry(7200)
        request.session['current_triangulation'] = ht.pk
        
        queryform = QueryForm()
        linkform = LinkForm()
        t = loader.get_template('query_or_select.html')
        c = RequestContext(request, {
                                    'queryform': queryform,
                                    'linkform': linkform,
                                    'helptext': reverse('HIT.Triangulator.views.helptext', args=['queryorselect']),
                                    'next': reverse('HIT.Triangulator.views.data_triangulation')})
        
        return HttpResponse(t.render(c))
    
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

# View for data triangulation
# Also creates a TriangulateResult in the database and stores its pk in the current session
@login_required
def data_triangulation(request):
    if 'current_triangulation' in request.session and\
        request.method == 'POST' and\
        request.POST['link']:
        
        l = Link(link = request.POST['link'])
        l.save()
        trian_result = TriangulateResult(link = l)
        trian_result.save()
        
        ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
        
        if ht.thesis_result:
            ht.thesis_result.delete() # Delete if already exists, this could happen from a page reload
        
        ht.thesis_result = trian_result
        ht.save()
        
        ##query, searchengines = data_triangulate(trian_result.link.link)
        ##res = {}
        ##for se in searchengines:
        ##    res[se.NAME] = {'enginelogo': se.LOGO, 'searchresults': se[:20]}
        
        t = loader.get_template('datatriangulator.html')
        c = RequestContext(request, {'results': None,
                                     'link': trian_result.link.link,
                                     'query': None,
                                     'helptext': reverse('HIT.Triangulator.views.helptext', args=['datatriangulation']),
                                     'next': reverse('HIT.Triangulator.views.investigator_triangulation')})
        return HttpResponse(t.render(c))

    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

@login_required
def investigator_triangulation(request):
    if 'current_triangulation' in request.session and request.method == 'POST':
        # Get current triangulation and corresponding result
        ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
        trian_result = ht.thesis_result
        # Delete trian_result.data_result if it exists
        # This is needed if the user used a page reload
        if trian_result.data_result:
            #TODO: this does not work: trian_result.data_result.links.delete(), find a way to delete all corresponding links
            trian_result.data_result.delete()
        # Store results of data triangulation
        links = request.POST.getlist('links')
        additional_links = request.POST['additional_links']
        reliability = request.POST['reliability']
        notes = request.POST['notes']
        dtr = data_triangulate_store(links, reliability, additional_links=additional_links, notes=notes)
        trian_result.data_result = dtr
        trian_result.save()
        investigatorform = InvestigatorForm()
        t = loader.get_template('investigatortriangulator.html')
        c = RequestContext(request, {'link': trian_result.link.link, 
                                     'investigatorform': investigatorform,
                                     'helptext': reverse('HIT.Triangulator.views.helptext', args=['investigatortriangulation']),
                                     'next': reverse('HIT.Triangulator.views.investigator_triangulation_results')})
        
        return HttpResponse(t.render(c))
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

@login_required
def investigator_triangulation_results(request):
    if 'current_triangulation' in request.session and request.method == 'POST':
        form = InvestigatorForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            # Get current triangulation and corresponding result
            ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
            trian_result = ht.thesis_result
            ir = investigator_triangulate(data['first_name'], data['last_name'], data['location'], data['domain'])
            t = loader.get_template('investigatortriangulatorresults.html')
            c = RequestContext(request, {'whoisdata': ir['whoisdata'], 
                                         'personlinks': ir['personlinks'], 
                                         'link': trian_result.link.link, 
                                         'data': data,
                                         'helptext': reverse('HIT.Triangulator.views.helptext', args=['investigatortriangulationresult']),
                                         'next': reverse('HIT.Triangulator.views.theory_triangulation')})
            
            return HttpResponse(t.render(c))
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

@login_required
def theory_triangulation(request):
    if 'current_triangulation' in request.session and request.method == 'POST':
        
        # Get current triangulation and corresponding result
        ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
        trian_result = ht.thesis_result
        
        # Delete trian_result.data_result if it exists
        # This is needed if the user used a page reload
        if trian_result.investigator_result:
            trian_result.investigator_result.links.all().delete()
            trian_result.investigator_result.delete()
        
        # Store results of investigator triangulation
        links = request.POST.getlist('links')
        whoisdata = request.POST['whoisdata']
        info = request.POST['additional_info']
        reliability = request.POST['reliability']
        notes = request.POST['notes']
        
        itr = investigator_triangulate_store(links, info, whoisdata, reliability=reliability, notes=notes)
        trian_result.investigator_result = itr
        trian_result.save()
        
        theory_result = theory_triangulate(trian_result.link.link)
        
        # User cannot edit the taglist, so let's store it immediatelly
        ttr = theory_triangulate_store(theory_result['taglist'])
        trian_result.theory_result = ttr
        trian_result.save()
        
        #Alchemy causal
        network = create_network(trian_result.link.link,'g')
        #Alchemy relations
        sentiment = sentiment_analysis(trian_result.link.link)
        
        
        t = loader.get_template('theorytriangulator.html')
        c = RequestContext(request, {'alchemy': network,
                                     'sentiment' : sentiment, 
                                     'link': trian_result.link.link,
                                     'helptext': reverse('HIT.Triangulator.views.helptext', args=['theorytriangulation']),
                                     'next': reverse('HIT.Triangulator.views.method_triangulation')})
        return HttpResponse(t.render(c))
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

def sentiment_analysis(link):
    result = ""
    try:
        alchemyObj = AlchemyAPI.AlchemyAPI()
        alchemyObj.loadAPIKey("api_key.txt")
        data = alchemyObj.URLGetTextSentiment(link);
        results = XML(data)
        result ="<h2>Sentiment: "
        result += results[4][0].text + "<h2><br><h2>Score: "
        result += results[4][1].text + "<h2><br><br>"
    except Exception:
        result = "<h2>Alchemy Error<h2>"
    return result


def create_network(link, graphPrefix):
    result = ""
    try:
        alchemyObj = AlchemyAPI.AlchemyAPI()
        alchemyObj.loadAPIKey("api_key.txt")
        data = alchemyObj.URLGetRelations(link)
        results = XML(data)
        relations = results[4]
        for relation in relations:
            children = relation.getchildren()
            if len(children) == 3:
                subject = relation[0]
                action = relation[1]
                object = relation[2]
            
                if isAllowedVerb(action[2][0].text) and isAllowedSubject(subject[0].text) and isAllowedSubject(object[0].text):
                        temp = graphPrefix + '.addEdge("'
                        temp += subject[0].text.replace("'", "").lower()
                        temp += '", "' + object[0].text.replace("'", "").lower()
                        temp +='", { directed : true, label : "'
                        temp += action[0].text.replace("'", "").lower()  + '"} );'
                        result += temp + '\n'
    except Exception:
        result = 'g.addEdge("AlchemyAPI", "an error", { directed : true, label : "has encountered"} );\n'
    
    return result

@login_required
def method_triangulation(request):
    if 'current_triangulation' in request.session and request.method == 'POST':
        
        # Get current triangulation and corresponding result
        ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
        trian_result = ht.thesis_result
        
        # Store results of investigator triangulation
        trian_result.theory_result.reliability = request.POST['reliability']
        trian_result.theory_result.notes = request.POST['notes']
        trian_result.theory_result.save()
        
        # Get all methods
        methods = Method.objects.all()
        
        t = loader.get_template('methodtriangulator.html')
        c = RequestContext(request, {'methods': methods,
                                     'link': trian_result.link.link,
                                     'helptext': reverse('HIT.Triangulator.views.helptext', args=['methodtriangulation']),
                                     'next': reverse('HIT.Triangulator.views.thesis_triangulate_summary')})
        return HttpResponse(t.render(c))
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

@login_required
def thesis_triangulate_summary(request):
    if 'current_triangulation' in request.session and request.method == 'POST':
        
        ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
        trian_result = ht.thesis_result
        
        methods = request.POST.getlist('methods')
        mtr = method_triangulate_store(methods, request.POST['reliability'], request.POST['notes'])
        trian_result.method_result = mtr
        trian_result.save()
        
        data_result = data_triangulate_result(trian_result)
        investigator_result = investigator_triangulate_result(trian_result)
        theory_result = theory_triangulate_result(trian_result)
        method_result = method_triangulate_result(trian_result)
        
         #Alchemy causal
        network = create_network(trian_result.link.link, 'g')
        #Alchemy relations
        sentiment = sentiment_analysis(trian_result.link.link)
        
        t = loader.get_template('thesistriangulatesummary.html')
        c = RequestContext(request, {'triangulation': ht,
                                     'triangulateresult': trian_result,
                                     'link': trian_result.link.link,
                                     'data_result': data_result,
                                     'investigator_result': investigator_result,
                                     'alchemy': network, 'sentiment' : sentiment, 'theory_result': theory_result,
                                     'helptext': reverse('HIT.Triangulator.views.helptext', args=['thesistriangulatesummary']),
                                     'method_result': method_result})
        return HttpResponse(t.render(c))
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

@login_required
def save_reliability_continue_antithesis(request):
    if 'current_triangulation' in request.session and request.method == 'POST' and request.POST['reliability']:
        ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
        trian_result = ht.thesis_result
        trian_result.reliability = request.POST['reliability']
        trian_result.save()
        return HttpResponseRedirect(reverse('HIT.Triangulator.views.start_triangulation_antithesis'))
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

@login_required
def save_reliability_stop(request):
    if 'current_triangulation' in request.session and request.method == 'POST' and request.POST['reliability']:
        ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
        trian_result = ht.thesis_result
        trian_result.reliability = request.POST['reliability']
        trian_result.save()
        return HttpResponseRedirect('/home/')
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

@login_required
def modify_thesis(request):
    if 'current_triangulation' in request.session:
        ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
        ht.delete()
        #TODO: completely remove hegelian triangulation
        return HttpResponseRedirect(reverse('HIT.Triangulator.views.start_triangulation'))
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')


'''----------------------------------------------- antithesis views -----------------------------------'''


@login_required
def start_triangulation_antithesis(request):
    t = loader.get_template('start_triangulation.html')
    f = StartAntithesisTriangulationForm()
    c = RequestContext(request, {'form': f, 'anti': "anti",
                                 'helptext': reverse('HIT.Triangulator.views.helptext', args=['starttriangulationantithesis']),
                                 'next': reverse('HIT.Triangulator.views.query_or_select_antithesis')})
    
    return HttpResponse(t.render(c))

'''
View for the start of the triangulation process.
Gives the user the choice to start triangulating a link or to search for a link on the internet through some keywords and metasearch
@param request Data about the request made by the user
'''
@login_required
def query_or_select_antithesis(request):
    f = StartAntithesisTriangulationForm(request.POST)
    if 'current_triangulation' in request.session and f.is_valid():
        ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
        ht.antithesis = f.cleaned_data['antithesis']
        ht.save()
    
        queryform = QueryForm()
        linkform = LinkForm()
        t = loader.get_template('query_or_select.html')
        c = RequestContext(request, {'anti': "anti",
                                    'queryform': queryform,
                                    'linkform': linkform,
                                    'helptext': reverse('HIT.Triangulator.views.helptext', args=['queryorselectantithesis']),
                                    'next': reverse('HIT.Triangulator.views.data_triangulation_antithesis')})
        
        return HttpResponse(t.render(c))
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

# View for data triangulation
# Also creates a TriangulateResult in the database and stores its pk in the current session
@login_required
def data_triangulation_antithesis(request):
    if 'current_triangulation' in request.session and\
        request.method == 'POST' and\
        request.POST['link']:
        
        l = Link(link = request.POST['link'])
        l.save()
        trian_result = TriangulateResult(link = l)
        trian_result.save()
        
        ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
        if ht.antithesis_result:
            ht.antithesis_result.delete() # Delete if already exists, this could happen from a page reload
        
        ht.antithesis_result = trian_result
        ht.save()
        
        #query, searchengines = data_triangulate(trian_result.link.link)
        #res = {}
        #for se in searchengines:
        #    res[se.NAME] = {'enginelogo': se.LOGO, 'searchresults': se[:20]}
        
        t = loader.get_template('datatriangulator.html')
        c = RequestContext(request, {'results': None, 'anti': "anti",
                                     'link': trian_result.link.link,
                                     'query': None,
                                     'helptext': reverse('HIT.Triangulator.views.helptext', args=['datatriangulationantithesis']),
                                     'next': reverse('HIT.Triangulator.views.investigator_triangulation_antithesis')})
        return HttpResponse(t.render(c))
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

@login_required
def investigator_triangulation_antithesis(request):
    if 'current_triangulation' in request.session and request.method == 'POST':
        
        # Get current triangulation and corresponding result
        ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
        trian_result = ht.antithesis_result
        
        # Delete trian_result.data_result if it exists
        # This is needed if the user used a page reload
        if trian_result.data_result:
            #trian_result.data_result.links.delete()
            trian_result.data_result.delete()
        
        # Store results of data triangulation
        links = request.POST.getlist('links')
        additional_links = request.POST['additional_links']
        reliability = request.POST['reliability']
        notes = request.POST['notes']
        
        dtr = data_triangulate_store(links, reliability, additional_links=additional_links, notes=notes)
        trian_result.data_result = dtr
        trian_result.save()
        
        investigatorform = InvestigatorForm()
        t = loader.get_template('investigatortriangulator.html')
        c = RequestContext(request, {'link': trian_result.link.link, 'anti': "anti", 
                                     'investigatorform': investigatorform,
                                     'helptext': reverse('HIT.Triangulator.views.helptext', args=['investigatortriangulationantithesis']),
                                     'next': reverse('HIT.Triangulator.views.investigator_triangulation_results_antithesis')})
        return HttpResponse(t.render(c))
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

@login_required
def investigator_triangulation_results_antithesis(request):
    if 'current_triangulation' in request.session and request.method == 'POST':
        form = InvestigatorForm(request.POST)
        
        if form.is_valid():
            data = form.cleaned_data
            
            # Get current triangulation and corresponding result
            ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
            trian_result = ht.antithesis_result
            
            ir = investigator_triangulate(data['first_name'], data['last_name'], data['location'], data['domain'])
            
            t = loader.get_template('investigatortriangulatorresults.html')
            c = RequestContext(request, {'whoisdata': ir['whoisdata'], 'anti': "anti",
                                         'personlinks': ir['personlinks'], 
                                         'link': trian_result.link.link, 
                                         'data': data,
                                         'helptext': reverse('HIT.Triangulator.views.helptext', args=['investigatortriangulationresultantithesis']),
                                         'next': reverse('HIT.Triangulator.views.theory_triangulation_antithesis')})
            
            return HttpResponse(t.render(c))
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

@login_required
def theory_triangulation_antithesis(request):
    if 'current_triangulation' in request.session and request.method == 'POST':
        
        # Get current triangulation and corresponding result
        ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
        trian_result = ht.antithesis_result
        
        # Delete trian_result.data_result if it exists
        # This is needed if the user used a page reload
        if trian_result.investigator_result:
            trian_result.investigator_result.links.all().delete()
            trian_result.investigator_result.delete()
        
        # Store results of investigator triangulation
        links = request.POST.getlist('links')
        whoisdata = request.POST['whoisdata']
        info = request.POST['additional_info']
        reliability = request.POST['reliability']
        notes = request.POST['notes']
        
        itr = investigator_triangulate_store(links, info, whoisdata, reliability=reliability, notes=notes)
        trian_result.investigator_result = itr
        trian_result.save()
        
        theory_result = theory_triangulate(trian_result.link.link)
        
        # User cannot edit the taglist, so let's store it immediatelly
        ttr = theory_triangulate_store(theory_result['taglist'])
        trian_result.theory_result = ttr
        trian_result.save()
        
        #Alchemy causal
        network = create_network(trian_result.link.link, 'g')
        #Alchemy relations
        sentiment = sentiment_analysis(trian_result.link.link)


        
        t = loader.get_template('theorytriangulator.html')
        c = RequestContext(request, {'alchemy': network, 'anti': "anti",
                                     'sentiment' : sentiment,
                                     'link': trian_result.link.link,
                                     'helptext': reverse('HIT.Triangulator.views.helptext', args=['theorytriangulationantithesis']),
                                     'next': reverse('HIT.Triangulator.views.method_triangulation_antithesis')})
        return HttpResponse(t.render(c))
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

@login_required
def method_triangulation_antithesis(request):
    if 'current_triangulation' in request.session and request.method == 'POST':
        
        # Get current triangulation and corresponding result
        #ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
        ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])

        trian_result = ht.antithesis_result
        
        # Store results of investigator triangulation
        trian_result.theory_result.reliability = request.POST['reliability']
        trian_result.theory_result.notes = request.POST['notes']
        trian_result.theory_result.save()
        
        # Get all methods
        methods = Method.objects.all()
        
        t = loader.get_template('methodtriangulator.html')
        c = RequestContext(request, {'methods': methods, 'anti': "anti",
                                     'link': trian_result.link.link,
                                     'helptext': reverse('HIT.Triangulator.views.helptext', args=['methodtriangulationantithesis']),
                                     'next': reverse('HIT.Triangulator.views.antithesis_triangulate_summary')})
        return HttpResponse(t.render(c))
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

@login_required
def antithesis_triangulate_summary(request):
    if 'current_triangulation' in request.session and request.method == 'POST':
        
        ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
        trian_result = ht.antithesis_result
        
        methods = request.POST.getlist('methods')
        mtr = method_triangulate_store(methods, request.POST['reliability'], request.POST['notes'])
        trian_result.method_result = mtr
        trian_result.save()
        
        data_result = data_triangulate_result(trian_result)
        investigator_result = investigator_triangulate_result(trian_result)
        theory_result = theory_triangulate_result(trian_result)
        method_result = method_triangulate_result(trian_result)
        
         #Alchemy causal
        network = create_network(trian_result.link.link,'g')
        #Alchemy relations
        sentiment = sentiment_analysis(trian_result.link.link)
        
        t = loader.get_template('antithesistriangulatesummary.html')
        c = RequestContext(request, {'triangulation': ht, 'anti': "anti",
                                     'helptext': reverse('HIT.Triangulator.views.helptext', args=['antithesistriangulatesummary']),
                                     'triangulateresult': trian_result,
                                     'link': trian_result.link.link,
                                     'data_result': data_result, 'alchemy' : network, 'sentiment' : sentiment,
                                     'investigator_result': investigator_result,
                                     'theory_result': theory_result,
                                     'method_result': method_result})
        return HttpResponse(t.render(c))
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

@login_required
def triangulate_summary(request):
    if 'current_triangulation' in request.session and request.method == 'POST':
        ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
        thesis_result = ht.thesis_result
        antithesis_result = ht.antithesis_result
        
        network1 = create_network(thesis_result.link.link,'g')
        sentiment1 = sentiment_analysis(thesis_result.link.link)
        
        
        thesis_results = {'link': thesis_result.link.link, 'alchemy1' : network1, 'sentiment1' : sentiment1,
                          'reliability': thesis_result.reliability,
                          'data_result': data_triangulate_result(thesis_result), 
                          'investigator_result': investigator_triangulate_result(thesis_result),
                          'theory_result': theory_triangulate_result(thesis_result),
                          'method_result': method_triangulate_result(thesis_result)}
        
        network2 = create_network(antithesis_result.link.link,'g2')
        sentiment2 = sentiment_analysis(antithesis_result.link.link)
        antithesis_results = {'link': antithesis_result.link.link, 'alchemy2' : network2, 'sentiment2' : sentiment2,
                              'reliability': antithesis_result.reliability,
                              'data_result': data_triangulate_result(antithesis_result),
                              'investigator_result': investigator_triangulate_result(antithesis_result),
                              'theory_result': theory_triangulate_result(antithesis_result),
                              'method_result': method_triangulate_result(antithesis_result)}
        
        synthesisform = SynthesisForm()
        
        t = loader.get_template('triangulatesummary.html')
        c = RequestContext(request, {'triangulation': ht,
                                     'thesis': thesis_results,
                                     'antithesis': antithesis_results,
                                     'helptext': reverse('HIT.Triangulator.views.helptext', args=['triangulatesummary']),
                                     'synthesisform': synthesisform})
        return HttpResponse(t.render(c))
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

@login_required
def save_synthesis(request):
    if 'current_triangulation' in request.session and request.method == 'POST':
        f = SynthesisForm(request.POST)
        if f.is_valid():
            ht = HegelianTriangulation.objects.get(id = request.session['current_triangulation'])
            ht.synthesis = f.cleaned_data['synthesis']
            ht.save()
            return HttpResponseRedirect('/home/')
    return HttpResponseServerError('Something seems to have gone wrong. Have you filled in the forms correctly? Please press the back button and try again.')

@login_required
def triangulate_result(request, id = -1):
    if id == -1:
        return HttpResponseServerError('Error on request, id does not exist')
    
    ht = HegelianTriangulation.objects.get(id=id)
    if not ht:
        return HttpResponseServerError('Error on request, id does not exist')
    
    if ht.user == request.user:
        thesis_result = ht.thesis_result
        antithesis_result = ht.antithesis_result
        
        thesis_results = None
        antithesis_results = None
        
        if thesis_result:
            thesis_results = {'link': thesis_result.link.link,
                              'reliability': thesis_result.reliability,
                              'data_result': data_triangulate_result(thesis_result),
                              'investigator_result': investigator_triangulate_result(thesis_result),
                              'theory_result': theory_triangulate_result(thesis_result),
                              'method_result': method_triangulate_result(thesis_result)}
        
        if antithesis_result:
            antithesis_results = {'link': antithesis_result.link.link,
                                  'reliability': antithesis_result.reliability,
                                  'data_result': data_triangulate_result(antithesis_result),
                                  'investigator_result': investigator_triangulate_result(antithesis_result),
                                  'theory_result': theory_triangulate_result(antithesis_result),
                                  'method_result': method_triangulate_result(antithesis_result)}
        
        
        t = loader.get_template('triangulateresult.html')
        c = RequestContext(request, {'triangulation': ht, 
                                     'helptext': reverse('HIT.Triangulator.views.helptext', args=['triangulateresult']),
                                     'thesis': thesis_results,
                                     'antithesis': antithesis_results})
        return HttpResponse(t.render(c))
    
    return HttpResponseForbidden('Triangulation is not yours!')

@login_required
def delete_triangulation(request, id = -1):
    if id == -1:
        return HttpResponseServerError('Error on request, id does not exist')
    
    ht = HegelianTriangulation.objects.get(id=id)
    if not ht:
        return HttpResponseServerError('Error on request, id does not exist')
    
    if ht.user == request.user:
        #TODO: delete complete triangulation
        ht.delete()
        return HttpResponseRedirect('/home/')
    
    return HttpResponseForbidden('Triangulation is not yours!')

@login_required
def helptext(request, name = ''):
    text = None
    
    try:
        text = HelpDocument.objects.get(name__iexact = name)
    except HelpDocument.DoesNotExist:
        return HttpResponseNotFound('Help document not found: '+name)
    
    t = loader.get_template('help.html')
    c = RequestContext(request,{'name': text.name, 'text': text.text})
    
    return HttpResponse(t.render(c))

'''
--------------------- AJAX methods ----------------------------
'''

'''
Adds a method to the database and returns the new id to the caller
'''
def add_method(request):
    if request.method == 'POST' and request.POST['method']:
        m = Method(method = request.POST['method'])
        m.save()
        return HttpResponse('{"id": '+str(m.pk)+', "method": "'+m.method+'"}', mimetype = 'application/json')
    else:
        return HttpResponseServerError('fail')

'''
Loads more results from metasearch and sends them to the caller
'''
        
def ajax_metasearch(request):
    if request.method == 'POST' and\
        request.POST['query'] and\
        request.POST['start'] and\
        request.POST['num']:
        
        start = int(request.POST['start'])
        num = int(request.POST['num'])
        
        engines = metasearch(request.POST['query'])
        res = []
        for e in engines:
            res.append({'logo': e.LOGO,
                        'name': e.NAME,
                        'results': e[start: start+num]})
        
        return HttpResponse(simplejson.dumps(res), mimetype='application/json')
    
'''
Registration form
'''    
def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/complete/")
    else:
        form = UserCreationForm()
    #return render_to_response("register.html", {
    #    'form': form,
    #})
    
    
    t = loader.get_template('register.html')
    c = RequestContext(request, {'form' : form})
    return HttpResponse(t.render(c))

def complete(request):
    t = loader.get_template('complete.html')
    c = RequestContext(request, {})
    return HttpResponse(t.render(c))

def isAllowedSubject(input):
    for string in forbiddenSubjects:
        if string.lower() == input.lower().strip():
            return False
    return True

def isAllowedVerb(input):
    for string in forbiddenVerbs:
        if string.lower() == input.lower().strip():
            return False
    return True
